package com.yu.websocket.controller;

import com.yu.bean.User;
import com.yu.service.UserInfoGetService;
import com.yu.websocket.common.WebSocketChatServer;
import com.yu.websocket.common.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
/**
 * @Auther: ole
 * @Date: 2021/3/1 0001 12:19
 * @Description:
 */
@Controller
public class SocketController {
    @Autowired
    UserInfoGetService UIS;

    @Resource
    private WebSocketChatServer webSocketChatServer;

    /**
     * 给指定用户推送消息
     * @param userName 用户名
     * @param message 消息
     * @throws IOException
     */
    @RequestMapping(value = "/socketChat", method = RequestMethod.GET)
    public void testSocket1(@RequestParam String userName, @RequestParam String message){
        webSocketChatServer.sendInfo(userName, message);
    }

    /**
     * 给所有用户推送消息
     * @param message 消息
     * @throws IOException
     */
    @RequestMapping(value = "/socketChat/all", method = RequestMethod.GET)
    public void testSocket2(@RequestParam String message){
        try {
            webSocketChatServer.onMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Resource
    private WebSocketServer webSocketServer;
    @RequestMapping("/socket")
    public String testSocket3(String username, String task){
        User u = UIS.getUser(username);
        u.setTask(task);
        UIS.updateuser(u);
        webSocketServer.sendInfo(username, task);
        return "redirect:/admin/info";
    }

    /**
     * 给所有用户推送任务
     * @param task 任务
     * @throws IOException
     */
    @RequestMapping(value = "/socket/all", method = RequestMethod.GET)
    public void testSocket4(@RequestParam String task){
        try {
            webSocketServer.onMessage(task);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
